﻿using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Data.Services.Common;
using System.Linq;
using System.ServiceModel.Web;
using System.Web;
using Ridofy.RiaClient.Web.Models;
using Ridofy.LastFm;

namespace Ridofy.RiaClient.Web.Services
{
    public class Ridofy : DataService<MusicEntities>
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(IDataServiceConfiguration config)
        {
            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
            config.UseVerboseErrors = true;
            config.SetEntitySetAccessRule("Songs", EntitySetRights.AllRead);
            config.SetServiceOperationAccessRule("GetSongsFromUser", ServiceOperationRights.All);
            config.SetServiceOperationAccessRule("RecentTracks", ServiceOperationRights.All);
            
        }

        [WebGet]
        public IQueryable<Songs> GetSongsFromUser(string userName)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException("Indique el UserName");
            }
            Track[] tracks = new LastFmRssClient().RecentTracks(userName);
            var result =  from t in tracks
                          where (!string.IsNullOrEmpty(t.Title))
                          select new Songs() { SongId = t.GetHashCode(),  Artist = t.Artist.Name, SongName = t.Title };
            return result.AsQueryable<Songs>();
        }

        [WebGet]
        public IEnumerable<Songs> RecentTracks(string user)
        {
            if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user es nulo");
            return new UserSongCollection(user).GetRecentSongs();
        }
    }
}
